package com.wangsd.web.api.controller;

import com.alibaba.fastjson.JSON;
import com.wangsd.common.basicbean.MyController;
import com.wangsd.common.basicbean.Result;
import com.wangsd.common.component.WxApiV3CouponService;
import com.wangsd.common.exception.BusinessException;
import com.wangsd.common.utils.DateUtils;
import com.wangsd.web.shop.entity.*;
import com.wangsd.web.shop.service.*;
import com.wangsd.web.sys.entity.SysCompany;
import com.wangsd.web.sys.entity.UploadFile;
import com.wangsd.web.sys.service.SysCompanyService;
import com.wangsd.web.sys.service.UploadFileService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Api(tags = "接口管理")
@RestController
@RequestMapping("/api/index")
@Slf4j
public class MiniIndexController extends MyController {
    @Value("${notify_url}")
    private String notify_url;
    @Autowired
    CustomerService customerService;
    @Autowired
    UploadFileService uploadFileService;
    @Autowired
    MemberService memberService;
    @Autowired
    CouponService couponService;
    @Autowired
    SysCompanyService companyService;
    @Autowired
    MerchantService merchantService;
    @Autowired
    CouponOrderService couponOrderService;
    @Autowired
    ActivityService activityService;
    @Autowired
    TradeService tradeService;
    @Autowired
    MemberQiandaoService memberQiandaoService;

    /**
     * 查询轮播和九宫格
     * @return
     */
    @GetMapping("/selectSwiperAndGrids")
    public Result selectSwiperAndGrids() {
        Customer customer = customerService.selectByMiniAppid(this.getMiniAppid());
        List<UploadFile> swipers = uploadFileService.selectSwiper(customer.getId(), 1);

        //List<Long> gridList = Arrays.asList(customer.getGrids().split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
        List<UploadFile> grids = uploadFileService.selectSwiper(customer.getId(), 5);

        Map map = new HashMap();
        map.put("swipers", swipers);
        map.put("grids", grids);
        return Result.success(map);
    }

    /**
     * 查询优惠券列表
     * @return
     */
    @GetMapping("/selectCouponList")
    public Result selectCouponList(String stockType) {
        Customer customer = customerService.selectByMiniAppid(this.getMiniAppid());
        Coupon query = new Coupon();
        query.setStockType(stockType);
        query.setStatus(2);
        query.setAvailableBeginTime(DateUtils.formatDatetime(new Date()));
        query.setAvailableEndTime(DateUtils.formatDatetime(new Date()));
        List<Coupon> list = couponService.selectPage(query, customer.getCode(), null, null);
        return Result.success(list);
    }

    /**
     * 查询优惠券详情
     * @param stockId
     * @return
     */
    @GetMapping("/selectCouponDetail")
    public Result selectCouponDetail(String stockId) {
        Coupon coupon = couponService.selectByStockId(stockId);
        if (coupon.getOnedayQuota() > 0) {
            long onedayCount = tradeService.selectOnedayQuota(stockId);
            coupon.setOnedayCount(coupon.getOnedayQuota() - onedayCount);
        }
        List<UploadFile> fileList = uploadFileService.selectByMaster(coupon.getId(), 4);
        coupon.setFileList(fileList);

        return Result.success(coupon);
    }

    /**
     * 发放(购买)优惠券
     * @param stockId
     * @return
     */
    @GetMapping("/sendCoupon")
    public Result sendCoupon(String stockId) {
        Member loginMember = getMiniUserInfo();
        Member member = memberService.selectByMiniOpenId(loginMember.getMiniOpenid());
        Coupon coupon = couponService.selectByStockId(stockId);

        Date date = new Date();
        if (DateUtils.dateDiff(coupon.getAvailableEndTime() + " 00:59:59", DateUtils.formatDatetime(date), 6) > 0) {
            throw new BusinessException("商品已过期");
        }

        if (coupon.getOnedayQuota() > 0) {
            long temp4 = tradeService.selectOnedayQuota(stockId);
            if (temp4 >= coupon.getOnedayQuota()) {
                throw new BusinessException("已超出今日限购数量，请明天继续！");
            }
        }

        long temp2 = tradeService.selectByStockIdAndMiniOpenid(coupon.getStockId(), member.getMiniOpenid());
        if (temp2 >= coupon.getMaxCouponsPerUser()) {
            throw new BusinessException("超出购买最大数量");
        }

        //临时解决时间问题，下架老券，上架新券。已购买老券不能购买新券
//        if ("1218400000000367".equals(coupon.getStockId())) {
//            long temp3 = tradeService.selectByStockIdAndMiniOpenid("1218400000000334", member.getMiniOpenid());
//            if (temp3 > 0) {
//                throw new BusinessException("超出购买最大数量");
//            }
//        }

        long temp = couponOrderService.selectByStockIdAndMiniOpenid(coupon.getStockId(), member.getMiniOpenid());
        if (temp >= coupon.getMaxCouponsPerUser()) {
            throw new BusinessException("超出购买最大数量");
        }

        if (coupon.getMaxCoupons() <= coupon.getDistributedCoupons()) {
            throw new BusinessException("已售完");
        }

        if (coupon.getType() == 1) { //免费领取优惠券(商家券不做免费领取)
            couponService.sendCoupon(coupon, member, null);
            return Result.success();
        }else if (coupon.getType() == 2) { //购买
            Object data = couponService.buyCoupon(coupon, member);
            return Result.success(data);
        }else if (coupon.getType() == 3) { //积分兑换
            String outTradeNo = couponService.exchangeCoupon(coupon, member);
            return Result.success(outTradeNo);
        }
        else if (coupon.getType() == 4) { //助力点兑换
            couponService.test20200329(coupon, member);
            return Result.success();
        }
        else {
            throw new BusinessException("商品类型错误");
        }
    }

    /**
     * 获取商家券发放参数
     * @param outTradeNo
     * @return
     */
    @GetMapping("/getMerCouponSign")
    public Result getMerCouponSign(String outTradeNo) {
        Trade trade = tradeService.selectByOutTradeNo(outTradeNo);
        if (trade.getStatus() == 1) {
            String[] codes = trade.getParentCode().split("-");
            Map<String, Object> resultMap = couponService.getMerCouponSign(codes[0], outTradeNo, trade.getProductNo());
            return Result.success(resultMap);
        }
        return Result.fail("未支付成功");
    }

    /**
     * 小程序发券成功后处理逻辑
     * @param outTradeNo
     * @param couponCode
     * @return
     */
    @GetMapping("/sendCouponSuccess")
    public Result sendCouponSuccess(String outTradeNo, String couponCode) {
        couponService.sendCouponSuccess(outTradeNo, couponCode);
        return Result.success();
    }

    /**
     * 查询品牌列表
     * @return
     */
    @GetMapping("/selectMerchant")
    public Result selectMerchant() {
        Customer customer = customerService.selectByMiniAppid(this.getMiniAppid());
        List<Merchant> list = merchantService.selectPage(new Merchant(), customer.getCode());
        return Result.success(list);
    }

    /**
     * 查询商户下面的优惠券
     * @param id
     * @return
     */
    @GetMapping("/selectMerchantDetail")
    public Result selectMerchantDetail(Long id) {
        Merchant merchant = merchantService.selectById(id);
        List<Coupon> couponList = couponService.selectAllByParentCode(merchant.getCode(), 2, null, null);
        merchant.setCouponList(couponList);
        return Result.success(merchant);
    }

    /**
     * 查询活动列表
     * @return
     */
    @GetMapping("/selectActivity")
    public Result selectActivity(Integer type) {
        Customer customer = customerService.selectByMiniAppid(this.getMiniAppid());
        Activity xsqgItem = activityService.selectByParentCode(customer.getCode(), type);
//        Activity xsmsItem = activityService.selectByParentCode(customer.getCode(), 4);
//        Map map = new HashMap();
//        map.put("xsqgItem", xsqgItem);
//        map.put("xsmsItem", xsmsItem);
        return Result.success(xsqgItem);
    }

    /**
     * 判断活动结束没有
     * @return
     */
    @GetMapping("/checkActivity")
    public Result checkActivity(Long activityId) {
        Activity activity = activityService.checkActivity(activityId);
        if (activity != null) {
            return Result.success();
        }
        return Result.fail("不在活动时间范围");
    }

    /**
     * 抽奖
     * @param activityId
     * @return
     */
    @GetMapping("/luckDraw")
    public Result luckDraw(Long activityId) {
        Member loginMember = this.getMiniUserInfo();
        Coupon coupon = activityService.luckDraw(activityId, loginMember.getMiniOpenid());
        String message = "";
        if (coupon.getType() != 4) {
            message = "恭喜抽中" + coupon.getStockName() + ",奖品已发放到卷包！";
        }else {
            message = "未中奖,感谢您支持本次活动！";
        }
        Result result = new Result(200, message, coupon);
        return result;
    }

    @GetMapping("/checkQiandao")
    public Result checkQiandao() {
        Member loginMember = this.getMiniUserInfo();
        boolean flag = memberQiandaoService.checkDate(loginMember.getMiniOpenid());
        return Result.success(flag);
    }

    @GetMapping("/qiandao")
    public Result qiandao() {
        Member loginMember = this.getMiniUserInfo();
        boolean flag = memberQiandaoService.checkDate(loginMember.getMiniOpenid());
        if (!flag) {
            throw new BusinessException("已签到");
        }
        memberService.qiandao(loginMember.getMiniOpenid());
        return Result.success();
    }
}
